﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skywave.Data
{
    public class DataContextHelper
    {
        private bool _UseProvidedDataContext;
        /// <summary>
        /// UseProvidedDataContext Property
        /// </summary>
        public bool UseProvidedDataContext
        {
            get { return _UseProvidedDataContext; }
            set { _UseProvidedDataContext = value; }
        }

        private bool _UseProvidedConnectionForDataContext;
        /// <summary>
        /// UseProvidedConnectionForDataContext Property
        /// </summary>
        public bool UseProvidedConnectionForDataContext
        {
            get { return _UseProvidedConnectionForDataContext; }
            set { _UseProvidedConnectionForDataContext = value; }
        }

        private System.Data.Common.DbConnection _ConnectionToUse;
        /// <summary>
        /// ConnectionToUse Property
        /// </summary>
        public System.Data.Common.DbConnection ConnectionToUse
        {
            get { return _ConnectionToUse; }
            set { _ConnectionToUse = value; }
        }
        
        public System.Data.Linq.DataContext GetDC(System.Data.Linq.DataContext _DC, string _ConnectionString, Type _DC_Type)
        {
            if (UseProvidedDataContext)
                return _DC;
            else if (UseProvidedConnectionForDataContext && ConnectionToUse != null)
            {
                bool isClosedBefore = ConnectionToUse.State == System.Data.ConnectionState.Closed;
                if (isClosedBefore)
                    ConnectionToUse.Open();
                ConnectionToUse.ChangeDatabase(new System.Data.SqlClient.SqlConnectionStringBuilder(_ConnectionString).InitialCatalog);
                return _DC_Type.Assembly.CreateInstance(_DC_Type.FullName, false, System.Reflection.BindingFlags.Default, null
                    , new object[] { _ConnectionToUse }, null, null) as System.Data.Linq.DataContext;
            }
            else
                return _DC_Type.Assembly.CreateInstance(_DC_Type.FullName, false, System.Reflection.BindingFlags.Default, null
                    , new object[] { _ConnectionString }, null, null) as System.Data.Linq.DataContext;
        }
    }
}
